//
//  ComposeViewController.swift
//  SinaWeibo
//
//  Created by 李旭阳 on 15/11/19.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
    }
    
    //MARK: 监听方法
    //关闭
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    //发布
    @objc private func send(){
        
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        guard let token = UserAccountViewModel().token else {
            SVProgressHUD.showErrorWithStatus("你还未登录")
            return
        }
        if selectorVC.imageList.count >= 1 {
            let imageData = UIImagePNGRepresentation(selectorVC.imageList[0])
            let parmaters = ["access_token": token, "status": textView.text]
            NetworkTools.sharedTools.uploadImage(urlString, parmaters: parmaters, imageData: imageData!, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("你还未登录")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发布微博成功")
            })
        }
    }
    
    //添加图片
    @objc private func selectPicture(){
        selectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(224 + 80 + 40)
        }
    }
    
    //MARK: 添加子控件
    private func setupUI(){
        setNavBar()
        setupTextView()
        setupToolBar()
        setSelectorView()
        //注册一个通知
        registerNotification()
    }
    
    //MARK: 设置 照片选择器
    private func setSelectorView(){
        //添加子视图控制器
        addChildViewController(selectorVC)
        //添加视图
        view.addSubview(selectorVC.view)
        // 调整视图层次结构
        view.bringSubviewToFront(toolBar)
        selectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(0)
        }
    }
    
    //MARK: 注册通知
    private func registerNotification(){
        //添加一个通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    //MARK: 移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //MARK: 通知响应方法
    //note 只是一个属性 用来接收 通知里面的信息
    @objc private func keyboardWillChange(note: NSNotification) {
        //获取动画事件
        let duration = note.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Double
        let rect = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //修改toolBar 的约束
        let offset = -screenH + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            //强制刷新
            self.view.layoutIfNeeded()
        }
    }
    
    //MARK: 懒加载
    private lazy var textView: UITextView = {
        let tv = UITextView()
        //设置键盘消失模型
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //设置弹簧效果
        tv.alwaysBounceVertical = true
        tv.delegate = self
        return tv
    }()
    
    private lazy var placeHolderLabel: UILabel = UILabel(title: "分享新鲜事...", size: 16, color: UIColor.lightGrayColor())
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //照片选择器
    private lazy var selectorVC: PictureSelectorViewController = PictureSelectorViewController()
}

extension ComposeViewController: UITextViewDelegate{
    func textViewDidChangeSelection(textView: UITextView){
        //设置 placeHolderLabel 隐藏 hasText 代表当前文本框是否有文字
        placeHolderLabel.hidden = textView.hasText()
        //设置发布按钮的交互
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
}

extension ComposeViewController{
    
    //MARK: 设置底部toolBar
    private func setupToolBar() {
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.right.left.equalTo(self.view)
            make.height.equalTo(40)
        }
        
        //设置 toolbar 的按钮 及点击事件
        var items = [UIBarButtonItem]()
        //添加 UI BarButtonItem
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background"],
            ["imageName": "compose_add_background"]]
        
        for dict in itemSettings {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(item)
            //实例化弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        //删除最后一个弹簧
        items.removeLast()
        toolBar.items = items
    }
    
    //MARK: 设置 导航条
    private func setNavBar(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        
        let titleLabel = UILabel(title: "发微博", size: 16, color: UIColor.darkGrayColor())
        let nameLabel = UILabel(title: UserAccountViewModel().userName ?? "", size: 14, color: UIColor.lightGrayColor())
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
    }
    
    //MARK: 设置 textView
    private func setupTextView(){
        view.addSubview(textView)
        textView.addSubview(placeHolderLabel)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(view.bounds.height / 3)
        }
        //添加占位文本
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(8)
        }
    }
    
}
